package a2;

import java.util.List;
import org.openrdf.repository.*;
import org.openrdf.repository.sparql.SPARQLRepository;
import org.openrdf.model.Value;
import org.openrdf.query.*;

public class Test {

	public static String query(String select, String query){
		Repository myRepository = new SPARQLRepository("http://vm15.cs.lth.se:8085/openrdf-sesame/repositories/KnowRob");
		RepositoryConnection con;
		String resultString = "";
		String prefix = "PREFIX :<http://ias.cs.tum.edu/kb/knowrob.owl#> " + 
				"PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#> " + 
				"PREFIX computable:<http://ias.cs.tum.edu/kb/computable.owl#> " + 
				"PREFIX owl2xml:<http://www.w3.org/2006/12/owl2-xml#> " + 
				"PREFIX xsd:<http://www.w3.org/2001/XMLSchema#> " + 
				"PREFIX owl:<http://www.w3.org/2002/07/owl#> " + 
				"PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#> " + 
				"PREFIX knowrob:<http://ias.cs.tum.edu/kb/knowrob.owl#>";

		try {
			myRepository.initialize();
			con = myRepository.getConnection();
			try {
				String queryString = prefix + "SELECT " + select + " WHERE { " + query + " }";
				TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SPARQL, queryString);
				TupleQueryResult result = tupleQuery.evaluate();
				List<String> bindingNames = result.getBindingNames();
				while (result.hasNext()) {
					BindingSet bindingSet = result.next();
					Value firstValue = bindingSet.getValue(bindingNames.get(0));
					resultString = firstValue.stringValue();
				}
				result.close();
			}finally {
				con.close();
				myRepository.shutDown();
			}
		}catch(Exception e){
			System.out.println("Something went wrong.");
		}	
		
		return resultString;
	}

	public static void main(String[] args) {
		String select = "?storageLoc";
		String s1 = "knowrob:DrinkingGlass rdfs:subClassOf*/owl:someValuesFrom ?storageLoc .";
		String s2 = "?node owl:someValuesFrom ?storageLoc .";
		String s3 = "?node owl:onProperty knowrob:storedAtPlace .";
		String result = query(select, s1+s2+s3);
		int i = result.indexOf('#');
		result = result.substring(i+1);
		System.out.println("RESULT ---> " + result);
		System.exit(0); // For some reason the program does not terminate automatically here
	}

}
